//
//  LTQPublishViewController.swift
//  WeiBoProject
//
//  Created by MAC on 16/3/5.
//  Copyright © 2016年 LTQ. All rights reserved.
//

import UIKit
import SnapKit
let holderString = "分享新鲜事..."

class LTQPublishViewController: UIViewController,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    
    
//    定义一个底部的约束值来记录相关变化
    var bottomConstraint: Constraint?
    
    override func viewDidLoad() {
        super.viewDidLoad()
 
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        setupTextView()
        setupToolBar()


        
        // Do any additional setup after loading the view.
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolBarFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    

    
//MARK:--设置Nav
   private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "publish")
        navigationItem.rightBarButtonItem?.enabled = false
//        创建一个label
        let titleLabel = UILabel(frame: CGRectMake(0, 0, 200, 44))
        titleLabel.textAlignment = .Center
        titleLabel.textColor = UIColor.orangeColor()
        titleLabel.numberOfLines = 0
        
        let username = LTQUserViewModel.shareInstance.userModel?.screen_name ?? ""
        titleLabel.text = "发布微博\n\(username)"
        
        let str = titleLabel.text
        
//        使用属性 修改发布微博四个字的属性
        let attribute = NSMutableAttributedString(string: str!)
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(15)], range:NSMakeRange(0, 4))//起始位置起的四个长度
        
        attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(13)], range: NSMakeRange(4, username.characters.count - 4))
//        将修改好的属性，重新赋值给titleLable的属性
        titleLabel.attributedText = attribute
        
        
        navigationItem.titleView = titleLabel
    }
    
//MARK:-- NavItem点击事件
    func dismiss(){
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    func publish(){
        
    }
    
//MARK:--设置TextView
    private func setupTextView(){
        
        /*
        思路一: 直接添加一个Label -- 练习一下
        思路二: 自己绘画
        */
        
        view.addSubview(textView)
        view.addSubview(photoView)
        textView.frame = view.frame
        textView.font = UIFont.systemFontOfSize(17)
        textView.holderString = holderString
        textView.delegate = self
        
//        滑动TextView时让键盘消失
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .OnDrag
        
        photoView.backgroundColor = UIColor.lightGrayColor()
        photoView.hidden = true
        photoView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.view.snp_center)
            make.width.equalTo(kUIScreenWidth - 2*LTQPhotoViewMargin)
            make.height.equalTo(kUIScreenWidth - 2*LTQPhotoViewMargin)
        }
        
    }
//    MARK: -- 设置底部ToolBar
//    需要自定义
    func setupToolBar(){
        toolBar.backgroundColor = UIColor.grayColor()
        
//        将控件添加到父视图上，并设置frame也就是约束
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            
             bottomConstraint = make.bottom.equalTo(view.snp_bottom).constraint
            
            make.height.equalTo(44)
        }
        
//        考虑将button添加到ToolBar上
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
//        定义一个数组,来接收items
        var items = [UIBarButtonItem]()
        
        for setting in itemSettings{
            
//            自定义button并设置图片
            let btn = UIButton(type: UIButtonType.Custom)
            
            btn.setImage(UIImage(named:setting["imageName"]!), forState: UIControlState.Normal)
            let btnName = setting["imageName"]
            btn.setImage(UIImage(named: "\(btnName)_highlighted"), forState: .Highlighted)
            
        
            if let action = setting["action"]{
                
                btn.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)

            }
//            将button转成item
            let item = UIBarButtonItem(customView: btn)
            btn.sizeToFit()
            
            items.append(item)
//            添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
//        item添加到toolBar上
        self.toolBar.items = items
        
    }
    
    //MARK:--选择图片的方法
    @objc private func choosePicture(){
        
 //        访问相机里面的图片,判断一下相机是否允许被访问
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            
            let imagePicker = UIImagePickerController()
            
            imagePicker.sourceType = .PhotoLibrary
            
//            想要选择相机里面的图片需要实现代理方法
            imagePicker.delegate = self
            
            
            //            如果可以进行页面跳转
            presentViewController(imagePicker, animated: true, completion: { () -> Void in
                
            })
            
        }
        
        
    }
    //MARK:--显示表情
    @objc private func inputEmoticon(){
        print("显示表情")
    }
    
    
    //MARK:--懒加载
    
    private lazy var textView:LTQTextView = LTQTextView()
    
    private lazy var toolBar:UIToolbar = UIToolbar()
 
    private lazy var photoView:LTQPhotoView = {
        
        let photo = LTQPhotoView()
        /*
        打破循环引用
        1.[weak self]
        2. [unowned self] self.choosePicture()
        3. 类似于OC weak var weakself = self ->  weakself?.choosePicture()
        */
        // 这个就是我们的闭包回调
        weak var weakself = self
        
        photo.selectPictureBlock = {[unowned self]() ->() in
            
            weakself?.choosePicture()
            
            }
        return photo
        
        }()
    
  
    
//MARK:--键盘改变的通知
    func changeToolBarFrame (noti:NSNotification){
        
//        print(noti.userInfo)
        if let info = noti.userInfo {
            /*
            弹出的时候
            UIKeyboardAnimationDurationUserInfoKey: 0.25,
            UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 465}, {414, 271}}
            
            //退出的时候
            UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 736}, {414, 271}},
            */
            // 需要把 NSRect 转换成CGRect .
           var endFrame = info["UIKeyboardFrameEndUserInfoKey"]?.CGRectValue
            if endFrame?.origin.y == kUIScreenHeight{
                
                toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    
                  self.bottomConstraint = make.bottom.equalTo(view.snp_bottom).constraint
                    
                })
                
                
            }else{
                toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    
                   self.bottomConstraint = make.bottom.equalTo(view.snp_bottom).offset(-endFrame!.size.height).constraint
                    
                })
            }
            let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
            UIView.animateWithDuration(duration, animations: { () -> Void in
                
                self.toolBar.layoutIfNeeded()
                
                }, completion: { (_) -> Void in
                    
            })
            
        }
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidChangeFrameNotification, object: nil)
    }
    

    

    
}
//    MARK:--选择相片的代理方法
extension LTQPublishViewController{
    /*
    注意: 你实现了代理方法,一定要调用 dismiss 方法, 不调用的话,不能自动消失
    */
//    选择了图片之后要进行的操作
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        
        photoView.hidden = false
        
        photoView.addImage(image)
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        print("消失")
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
}

//MARK:--TextView实现代理
extension LTQPublishViewController{
    
//    代理方法可以检测输入项的变化
    func textViewDidChange(textView: UITextView) {
        
        if textView.hasText(){
            self.textView.holderString = ""
        }else{
            self.textView.holderString = holderString
        }
//        重绘
        self.textView.setNeedsDisplay()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
}